package com.qingluan.dd.InetTool;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.qingluan.arguments.ARGUMENTS;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

public class BitmapDownloader {

	private final static String TAG = BitmapDownloader.class.getName();
	
	public static void  Download(Context context ,String picture_path,final CallBack callBack){
		
		AsyncHttpClient Client = new AsyncHttpClient();
		RequestParams request = new RequestParams();
		JSONObject json = new JSONObject();
		
		try {
			json.put("picture_path", picture_path);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		request.put(ARGUMENTS.POST_ARGUMENT_PICTURE,json.toString());
		String[] allowType = new String[]{"image/png; charset=utf-8"};
		Log.d("CACHE", "picture get iP : .."+picture_path);
		if (isNetworkAvailable(context)){
			Toast.makeText(context, "Internet ok....", Toast.LENGTH_SHORT).show();
			Client.post(ARGUMENTS.PICTURE_IP, request,new BinaryHttpResponseHandler(allowType){
				@Override
				public void onSuccess(byte[] data){
					callBack.onDataGot(data);
				}
				
				
				@Override
				public void onFailure(int statusCode, Header[] headers
						, byte[] binaryData, Throwable error){
					Log.d("I_CACHE","error"+error.toString());
					try{
						for (Header head : headers){
							Log.d(TAG,head.getName() + "/"+head.getValue());
						}
					}catch (NullPointerException e){
						Log.d("CACHE",e.toString());
					}
				
				}
			});
		}else {
			Toast.makeText(context, "No internet", Toast.LENGTH_SHORT).show();
		}
		
	}
	
	public interface CallBack{
		public void onDataGot(byte[] data);
	}
	  
	public static boolean isNetworkAvailable( Context context ) {
		  ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		  if (connectivity == null) {
			  return false;
		  } else {
			  NetworkInfo[] info = connectivity.getAllNetworkInfo();
			  if (info != null) {
				  for (int i = 0; i < info.length; i++) {
					  if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						  return true;
					  }
				  }
			  }
		  }
		  return false;
	}

}
